package com.weilx959.spt.core.serialize;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Base64;
import java.util.Objects;

/**
 * Java 对象序列化器
 *
 * @param <T> 待序列化的对象类型
 */
@Slf4j
public class JavaSerializer<T> implements ValueSerializer<T>, ValueDeserializer<T> {
    @Override
    public T deserialize(String value) {
        if (StringUtils.isEmpty(value)) {
            return null;
        }
        try (ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(Base64.getDecoder().decode(value)))) {
            return (T) ois.readObject();
        } catch (Exception e) {
            log.error("JavaSerializer deserialize error", e);
            throw new IllegalArgumentException("JavaSerializer deserialize error", e);
        }
    }

    @Override
    public String serialize(T value) {
        if (Objects.isNull(value)) {
            return null;
        }
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(bos)) {
            oos.writeObject(value);
            return Base64.getEncoder().encodeToString(bos.toByteArray());
        } catch (Exception e) {
            log.error("JavaSerializer serialize error", e);
            throw new IllegalArgumentException("JavaSerializer serialize error", e);
        }
    }
}
